package com.xm.common.listener;

import com.alibaba.fastjson2.JSON;
import com.xm.common.entity.dto.Client;
import com.xm.common.entity.vo.request.CodeVO;
import com.xm.common.entity.vo.request.RuntimeDetailVO;
import com.xm.common.service.ClientService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class KafkaConsumer {

    @Resource
    JavaMailSender sender;

    @Resource
    ClientService service;

    @Value("${spring.mail.username}")
    String username;

//    @KafkaListener(topics = "monitor")
    public void consume(String data) {
        RuntimeDetailVO runtimeDetailVO = JSON.parseObject(data, RuntimeDetailVO.class);
        Client client = service.findClientByToken(runtimeDetailVO.getToken());
        service.updateRuntimeDetail(runtimeDetailVO, client);
        log.info("收到消息: {}", data);
    }

    @KafkaListener(topics = "email")
    public void sendMailMessage(String data) {
        CodeVO vo = JSON.parseObject(data, CodeVO.class);

        String email = vo.getEmail();
        int code = vo.getCode();
        SimpleMailMessage message = switch (vo.getType()) {
            case "reset" ->
                    createMessage("您的密码重置邮件",
                            "你好，您正在执行重置密码操作，验证码: "+code+"，有效时间3分钟，如非本人操作，请无视。",
                            email);
            case "modify" ->
                    createMessage("您的邮件修改验证邮件",
                            "您好，您正在绑定新的电子邮件地址，验证码: "+code+"，有效时间3分钟，如非本人操作，请无视",
                            email);
            default -> null;
        };
        if(message == null) return;
        sender.send(message);
    }

    /**
     * 快速封装简单邮件消息实体
     * @param title 标题
     * @param content 内容
     * @param email 收件人
     * @return 邮件实体
     */
    private SimpleMailMessage createMessage(String title, String content, String email){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(title);
        message.setText(content);
        message.setTo(email);
        message.setFrom(username);
        return message;
    }
}
